/*
 * @Author: dagu 243065157@qq.com
 * @Date: 2025-02-12 15:17:58
 * @LastEditors: dagu 243065157@qq.com
 * @LastEditTime: 2025-02-14 12:02:05
 * @FilePath: \format-bug-msg\electron\main.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import Store from 'electron-store';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 初始化存储
const store = new Store();

let mainWindow = null;

function createWindow() {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    title: '错误信息生成器',
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  // 设置窗口标题
  mainWindow.setTitle('错误信息生成器');

  // 加载应用
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173');
    // 打开开发者工具
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }

  // 监听窗口关闭事件
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

// 当 Electron 完成初始化时被调用
app.whenReady().then(createWindow);

// 当所有窗口被关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});

// IPC 通信示例
ipcMain.on('save-bug', (event, bugData) => {
  store.set('bugs', bugData);
  event.reply('save-bug-reply', { success: true });
});

ipcMain.on('get-bugs', event => {
  const bugs = store.get('bugs', []);
  event.reply('get-bugs-reply', bugs);
});
